'use client'

import { FormEvent, useMemo, useRef, useState } from 'react'
import { useChat } from 'ai/react'
import ReactMarkdown from 'react-markdown'
import { Card, Button, Input, Select, Space, Typography, Divider, message } from 'antd'
import { CopyOutlined, SendOutlined, StopOutlined } from '@ant-design/icons'

const { TextArea } = Input
const { Title, Text } = Typography
const { Option } = Select

const TOOL_PRESETS = {
  rewrite: '请在不改变含义的前提下，重写并提升流畅度与可读性。',
  expand: '请在原意基础上扩写，补充细节、示例与过渡，使内容更完整。',
  summarize: '请提炼要点，输出分点式摘要，并给出简短标题。',
  translate: '请将内容翻译为中文，保留术语并润色语序。'
}

type Mode = keyof typeof TOOL_PRESETS | 'general'

export default function WritingAssistant() {
  const [mode, setMode] = useState<Mode>('general')
  const [tone, setTone] = useState('neutral')
  const inputRef = useRef<HTMLTextAreaElement | null>(null)

  const { messages, input, setInput, handleSubmit, isLoading, stop } = useChat({
    api: '/api/generate',
    body: { mode, tone },
    onFinish: () => {
      // 自动滚动到底部
      const el = document.getElementById('chat-end')
      el?.scrollIntoView({ behavior: 'smooth', block: 'end' })
    }
  })

  const placeholder = useMemo(() => {
    if (mode === 'rewrite') return '粘贴要改写的文本…'
    if (mode === 'expand') return '粘贴要扩写的文本…'
    if (mode === 'summarize') return '粘贴要总结的文本…'
    if (mode === 'translate') return '粘贴要翻译的文本…'
    return '描述你的写作需求或粘贴文本…'
  }, [mode])

  function onQuickToolClick(m: Mode) {
    setMode(m)
    // 将预设提示塞到输入框首行（可编辑）
    const preset = TOOL_PRESETS[m as keyof typeof TOOL_PRESETS]
    setInput(preset ? `${preset}\n\n` : '')
    inputRef.current?.focus()
  }

  function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    // 以用户输入为准；保持对话上下文
    handleSubmit(e)
  }

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text)
    message.success('已复制到剪贴板')
  }

  return (
    <div>
      <Title level={2}>写作助手</Title>
      <Text type="secondary">AI驱动的智能写作工具</Text>
      
      <Divider />
      
      {/* 工具栏 */}
      <Card style={{ marginBottom: 16 }}>
        <Space direction="vertical" style={{ width: '100%' }}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
            <Button onClick={() => onQuickToolClick('rewrite')} type="default">改写</Button>
            <Button onClick={() => onQuickToolClick('expand')} type="default">扩写</Button>
            <Button onClick={() => onQuickToolClick('summarize')} type="default">总结</Button>
            <Button onClick={() => onQuickToolClick('translate')} type="default">翻译</Button>
            <span style={{ marginLeft: 'auto', fontSize: '14px', color: '#666' }}>
              模式：{mode}
            </span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <Text style={{ fontSize: '14px', color: '#666' }}>语气：</Text>
            <Select 
              value={tone} 
              onChange={setTone} 
              style={{ width: 120 }}
            >
              <Option value="neutral">中性</Option>
              <Option value="formal">正式</Option>
              <Option value="friendly">友好</Option>
              <Option value="academic">学术</Option>
            </Select>
            {isLoading && (
              <Button 
                onClick={() => stop()} 
                icon={<StopOutlined />}
                style={{ marginLeft: 'auto' }}
              >
                停止
              </Button>
            )}
          </div>
        </Space>
      </Card>

      {/* 输入区 */}
      <Card style={{ marginBottom: 16 }}>
        <form onSubmit={onSubmit}>
          <Space direction="vertical" style={{ width: '100%' }}>
            <TextArea
              ref={inputRef}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder={placeholder}
              autoSize={{ minRows: 6, maxRows: 10 }}
            />
            <div style={{ display: 'flex', gap: 8 }}>
              <Button 
                type="primary" 
                htmlType="submit" 
                icon={<SendOutlined />}
                loading={isLoading}
              >
                生成
              </Button>
              <Button 
                onClick={() => copyToClipboard(input)}
                icon={<CopyOutlined />}
              >
                复制输入
              </Button>
            </div>
          </Space>
        </form>
      </Card>

      {/* 对话区 */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {messages.map(m => (
          <Card 
            key={m.id} 
            size="small"
            style={{ 
              borderColor: m.role === 'user' ? '#d9d9d9' : '#f0f0f0',
              backgroundColor: m.role === 'user' ? '#fff' : '#fafafa'
            }}
          >
            <div style={{ marginBottom: 8, fontSize: '12px', color: '#666' }}>
              {m.role === 'user' ? '你' : '助手'}
            </div>
            <div style={{ lineHeight: 1.6 }}>
              <ReactMarkdown>{m.content || ''}</ReactMarkdown>
            </div>
            {m.role !== 'user' && (
              <div style={{ marginTop: 12 }}>
                <Button 
                  size="small"
                  onClick={() => copyToClipboard(m.content || '')}
                  icon={<CopyOutlined />}
                >
                  复制输出
                </Button>
              </div>
            )}
          </Card>
        ))}
        <div id="chat-end" />
      </div>
    </div>
  )
} 